package vip.fastgo.retroid.android.gamebox.view.activity

import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import androidx.fragment.app.Fragment
import com.google.android.material.navigation.NavigationBarView
import vip.fastgo.retroid.android.gamebox.R
import vip.fastgo.retroid.android.gamebox.databinding.ActivityMainBinding
import vip.fastgo.retroid.android.gamebox.view.fragment.CircleFragment
import vip.fastgo.retroid.android.gamebox.view.fragment.HomeFragment
import vip.fastgo.retroid.android.gamebox.view.fragment.MineFragment

class MainActivity : BaseActivity<ActivityMainBinding>(), View.OnClickListener,
    NavigationBarView.OnItemSelectedListener {

//    external fun stringFromJNI(): String
    private val fragments = ArrayList<Fragment>()

//    companion object {
//        // Used to load the 'gamebox' library on application startup.
//        init {
//            System.loadLibrary("gamebox")
//        }
//    }

    override fun initBinding(): ActivityMainBinding {
        return ActivityMainBinding.inflate(layoutInflater)
    }

    override fun initView(savedInstanceState: Bundle?) {
        binding.mainTabNav.setOnItemSelectedListener(this)

        fragments.add(HomeFragment.newInstance())
        fragments.add(CircleFragment.newInstance())
        fragments.add(MineFragment.newInstance())

        changeTab(0)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.sample_text -> {
                startActivity(Intent(this, GameActivity::class.java))
            }
            else -> {}
        }
    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.menu_tab_home -> {
                changeTab(0)
            }
            R.id.menu_tab_circle -> {
                changeTab(1)
            }
            R.id.menu_tab_mine -> {
                changeTab(2)
            }
            else -> {}
        }
        return true
    }

    /**
     * 切换Fragment
     *
     * @param position 下标
     */
    private fun changeTab(position: Int) {
        val size = fragments.size
        for (i in 0 until size) {
            val fragment = fragments[i]
            if (i == position) {
                if (!fragment.isAdded) {
                    supportFragmentManager.beginTransaction().add(R.id.main_frame, fragment).commit()
                }
                supportFragmentManager.beginTransaction().show(fragment).commit()
            } else {
                supportFragmentManager.beginTransaction().hide(fragment).commit()
            }
        }
    }
}